package com.nononsenseapps.feeder.db.ext

import androidx.room.TypeConverter
import com.gitee.wsl.ext.base.toEpochMilliseconds
import com.nononsenseapps.feeder.util.sloppyLinkToStrictURLNoThrows
import io.ktor.http.Url
import kotlinx.datetime.Instant
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime


class Converters {

    @TypeConverter
    fun dateTimeFromString(value: String?): LocalDateTime? {
        var dt: LocalDateTime? = null
        if (value != null) {
            try {
                dt = LocalDateTime.parse(value)
            } catch (_: Throwable) {

            }
        }
        return dt
    }

    @TypeConverter
    fun stringFromDateTime(value: LocalDateTime?): String? = value?.toString()

    @TypeConverter
    fun stringFromURL(value: Url?): String? = value?.toString()

    @TypeConverter
    fun urlFromString(value: String?): Url? = value?.let { sloppyLinkToStrictURLNoThrows(it) }

    @TypeConverter
    fun dateTimeFromLong(value: Long?): LocalDateTime? =
            try {
                value?.let { Instant.fromEpochMilliseconds(it).toLocalDateTime(TimeZone.UTC) }
            } catch (t: Throwable) {
                null
            }

    @TypeConverter
    fun longFromDateTime(value: LocalDateTime?): Long? = value?.toEpochMilliseconds()

    @TypeConverter
    fun instantFromLong(value: Long?): Instant? =
        try {
            value?.let { Instant.fromEpochMilliseconds(it) }
        } catch (t: Throwable) {
            null
        }

    @TypeConverter
    fun longFromInstant(value: Instant?): Long? = value?.toEpochMilliseconds()

}